package com.example.springboot.services.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot.domain.PageBean;
import com.example.springboot.domain.Role;
import com.example.springboot.dto.MenusDTO;
import com.example.springboot.mapper.RoleMapper;
import com.example.springboot.services.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.LinkedList;
import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    RoleMapper roleMapper;

    @Override
    public PageBean<Role> queryAllRole(Integer page, Integer pagesize) {

        IPage iPage = roleMapper.selectPage(new Page(page, pagesize), null);

        PageBean<Role> data = new PageBean<>();
        data.setData(iPage.getRecords());
        data.setTotal((int) iPage.getTotal());

        return data;
    }

    @Override
    public List<Integer> queryRoleMenuIds(Integer roleId) {

        List<Integer> menuIds = roleMapper.queryRoleMenuIds(roleId);
        return menuIds;
    }

    @Override
    public Boolean updatePermission(MenusDTO menusDTO) {
        /**
         * 比较当前权限和要修改的权限，生成增添列表和删除列表
         */
        List<Integer> updateIds = menusDTO.getMenuIds();
        List<Integer> curIds = roleMapper.queryRoleMenuIds(menusDTO.getRoleId());
        LinkedList<Integer> addList = new LinkedList<>();
        LinkedList<Integer> removeList = new LinkedList<>();
        for (Integer curId : curIds) {
            if(!(updateIds.contains(curId))){
                removeList.add(curId);
            }
        }
        for (Integer updateId : updateIds) {
            if(!(curIds.contains(updateId))){
                addList.add(updateId);
            }
        }

        //删除修改权限中没有的权限
        if(removeList.size() != 0){
            roleMapper.removePermission(removeList, menusDTO.getRoleId());
        }

        //增加修改权限中新添部分
        if(addList.size() !=0 ){
            roleMapper.addPermission(addList,menusDTO.getRoleId());
        }

        return true;
    }
}
